﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")

/**
*    @file:    authcontroller.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2024-11-03  14:57
*/
#include "authcontroller.h"
#include "user.h"
#include "httpresponse.h"
#include "responesutils.h"
#include "cookieutils.h"
#include "qjwtutils.h"

#include <QJsonDocument>
#include <userservice.h>

AuthController::AuthController(QObject *parent): HttpRequestHandler(parent)
{

}

AuthController::~AuthController()
{

}

void AuthController::service(HttpRequest &request, HttpResponse &response)
{
    QString path = request.getPath();
    QStringList pathList = path.split("/");
    if (pathList.size() < 3)
    {
        this->returnError(response);
        return;
    }
    QString method = pathList.value(3);
    QByteArray responseMsg;
    QString methodType = request.getMethod();

    if (methodType == "GET")
    {
        if (method == "codes")
        {
            return codes(request, response);
        }
    }
    else if (methodType == "POST")
    {
        if (method == "login")
        {
            return login(request, response);
        }else if(method == "register"){
            return m_register(request,response);
        }
    }
    this->returnError(response);
}

void AuthController::login(HttpRequest &request, HttpResponse &response)
{
    QByteArray body = request.getBody();
    if(body.isEmpty()){
        ResponesUtils::paramErrorResponse(response,"请求体为空！");
    }

    QJsonParseError jsonpe;
    QJsonObject jsonObject = QJsonDocument::fromJson(body, &jsonpe).object();
    User user;
    user.fromJsonObject(jsonObject);

    if(user.getPassword().isEmpty() || user.getUsername().isEmpty()){
        return ResponesUtils::paramErrorResponse(response,"Username and password and  are required");
    }

    //去数据库查询用户
    UserService userService;
    if(!userService.getOne(user)){
        return ResponesUtils::paramErrorResponse(response,"数据库异常！");
    }
    if(user.getId() == 0){
        //清除刷新令牌Cookie
        return ResponesUtils::forbiddenResponse(response,QString("用户名或密码错误！"));
    }
    if(user.getStatus() != USER_STATUS_ENABLED){
        if(user.getStatus() == USER_STATUS_DISABLED){
            //清除刷新令牌Cookie
            return ResponesUtils::forbiddenResponse(response,QString("用户名已被禁用，请联系管理员处理！"));
        }
        if(user.getStatus() == USER_STATUS_DELETED){
            //清除刷新令牌Cookie
            return ResponesUtils::forbiddenResponse(response,QString("用户已被删除，请重新注册！"));
        }
    }

    user.setPassword("******");//隐藏密码
    QJsonObject userJsonObject = user.toJsonObject();
//    qDebug() << __FUNCTION__ << userJsonObject;

    //生成访问令牌 generateAccessToken
    QByteArray accessToken = QJwtUtils::generateAccessToken(userJsonObject).toLatin1();
//    qDebug() << "accessToken=" << accessToken;
    //生成刷新令牌 generateRefreshToken
    QByteArray refreshToken = QJwtUtils::generateRefreshToken(userJsonObject).toLatin1();
    qDebug() << "refreshToken=" << refreshToken;
    //设置刷新令牌
    CookieUtils::setRefreshTokenCookie(response,refreshToken);
    QString token = QString(refreshToken);
    qDebug() << QJwtUtils::verifyRefreshToken(token);
    //返回结果
    userJsonObject.insert("accessToken",QString(accessToken));
    ResponesUtils::useResponseSuccess(response,userJsonObject);
}

void AuthController::codes(HttpRequest &request, HttpResponse &response)
{
    QString authHeader = request.getHeader("Authorization");
    //权限找不到或者权限字符串头找不到
    if(authHeader.isEmpty() || authHeader.indexOf("Bearer ") == -1 || authHeader.split(" ").size() < 2){
        qDebug() << "权限找不到或者权限字符串头找不到";
        return ResponesUtils::unAuthorizedResponse(response);

    }
    QString token = authHeader.split(" ")[1];
    QJsonObject jsonObject= QJwtUtils::verifyAccessToken(token);
    User user;
    user.fromJsonObject(jsonObject);
    if(user.isEmpty()){
        return ResponesUtils::unAuthorizedResponse(response);
    }
    QStringList strList;
    strList << "AC_100100" << "AC_100110" << "AC_100120" << "AC_100010";
    QJsonArray jsonArrery = QJsonArray::fromStringList(strList);
    ResponesUtils::useResponseSuccess(response,jsonArrery);
}

void AuthController::logout(HttpRequest &request, HttpResponse &response)
{
    if(CookieUtils::getRefreshTokenFromCookie(request).isEmpty()){
        ResponesUtils::useResponseSuccess(response,"退出成功！");
        return;
    }
    CookieUtils::clearRefreshTokenCookie(response);
    ResponesUtils::useResponseSuccess(response,"退出成功！");
    return;
}

void AuthController::m_register(HttpRequest &request, HttpResponse &response)
{
    QByteArray body = request.getBody();
    if(body.isEmpty()){
        ResponesUtils::paramErrorResponse(response,"请求参数异常！");
        return;
    }

    QJsonObject jsonObj;
    QJsonParseError jsonpe;
    QJsonObject jsonObject = QJsonDocument::fromJson(body, &jsonpe).object();
    QString password = jsonObject.value("password").toString();
    QString confirmPassword = jsonObject.value("confirmPassword").toString();

    //判断密码和确认密码一致性
    if(password.compare(confirmPassword) != 0){
        return ResponesUtils::paramErrorResponse(response,"密码和确认密码不一致！");
    }
    User user;
    UserService userService;
    user.setUsername(jsonObject.value("username").toString());
    if(!userService.getOne(user)){
        return ResponesUtils::paramErrorResponse(response,"数据库异常！");
    }
    if(user.getId() != 0){
        return ResponesUtils::paramErrorResponse(response,"该用户名已经注册了！");
    }
    user.fromJsonObject(jsonObject);
    user.setStatus(USER_STATUS_ENABLED);
    if(!userService.saveOne(user)){
        return ResponesUtils::paramErrorResponse(response,"数据库异常！");
    }
    if(!userService.getOne(user)){
        return ResponesUtils::paramErrorResponse(response,"数据库异常！");
    }
    if(user.getId() == 0){
        //清除刷新令牌Cookie
        CookieUtils::clearRefreshTokenCookie(response);
        return ResponesUtils::forbiddenResponse(response,QString("注册失败！"));
    }
    //隐藏密码
    user.setPassword("******");
    QJsonObject userJson = user.toJsonObject();

    //生成访问令牌 generateAccessToken
    QByteArray accessToken = QJwtUtils::generateAccessToken(userJson).toLatin1();
    qDebug() << "accessToken=" << accessToken;
    //生成刷新令牌 generateRefreshToken
    QByteArray refreshToken = QJwtUtils::generateRefreshToken(userJson).toLatin1();
    qDebug() << "refreshToken=" << refreshToken;
    //设置刷新令牌
    CookieUtils::setRefreshTokenCookie(response,refreshToken);
    //返回结果
    QJsonObject obj = user.toJsonObject();
    obj.insert("accessToken",QString(accessToken));
    ResponesUtils::useResponseSuccess(response,obj);
}
